import 'package:package_info_plus/package_info_plus.dart';
import 'package:universal_io/io.dart';
import '../../config.dart';
import '../common.dart';


const APP_NAME = "jm_translate";

class AppVersion {
  static const tag = "AppVersion";

  static var version = ""; //当前版本
  static var buildNumber = ""; //当前版本号
  static var appName = ""; //APP名称
  static var packageName = ""; //包名

  static var newVersion = ""; //最新版本
  static var newVersionDes = ""; //最新版本描述
  static String downloadurl = ""; //最新版本下载地址

  static var isNew = false; //是否有新版本
  static var isPrompt = false; //是否弹窗提醒
  static var isForcibly = false; //是否强制更新

  static init() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    appName = packageInfo.appName;
    packageName = packageInfo.packageName;
    version = packageInfo.version;
    buildNumber = packageInfo.buildNumber;
  }

  static getNew({bool isShowDialog = true}) {
    if (isShowDialog) {
      Show.loading();
    }

    String platformStr = "";
    if (Platform.isAndroid) {
      if (JmConfig.googlePlay) {
        platformStr = "googleplay";
      } else {
        platformStr = "android";
      }
    } else {
      platformStr = "ios";
    }
    Api.request("https://www.senlea.cn:29103/getupdate", query: {
      "name": APP_NAME,
      "CurrentVersion": int.tryParse(buildNumber),
      "platform": platformStr,
    }).then((value) {
      if (isShowDialog) {
        Show.dismiss();
      }

      //logd(tag, "value:"+value.toString());
      Result result = Result.fromJsonData(value);
      if (result.isSuccess) {
        downloadurl = result.data["downloadurl"] ?? "";
        newVersionDes = result.data["updatedes"] ?? "";
        newVersion = result.data["newversion"] ?? "";
        isNew = result.data["isnew"] ?? false;
        isPrompt = result.data["isprompt"] ?? false;
        isForcibly = result.data["isforcibly"] ?? false;

        if (isNew) {
          if (isShowDialog) {
            showUpdateDialog();
          }
        } else {
          if (isShowDialog) {
            Show.success("当前是最新版");
          }
        }
      }
    }).onError((error, stackTrace) {
      if (isShowDialog) {
        Show.error("获取应用版本错误:" + error.toString());
      }

      logw(tag, "连接错误:" + error.toString());
    });
  }

  static showUpdateDialog() {
    if (isNew) {
      // Get.dialog(MyDialog(
      //   title: "发现新版本",
      //   middleText: newVersionDes,
      //   leftButtonText: "暂不升级",
      //   rightButtonText: "立即升级",
      //   onLeftTap: () {
      //     Get.back();
      //   },
      //   onRightTap: () {
      //     Get.back();
      //     if (downloadurl.isNotEmpty) {
      //       openUrl(downloadurl);
      //     } else {
      //       loge(tag, "下载地址错误");
      //     }
      //   },
      // ));
    }
  }
}
